const db = require('./backend/config/db');

async function testUserListLogic() {
  try {
    // 模拟请求参数
    const page = 1;
    const limit = 20;
    const keyword = '';
    const offset = (page - 1) * limit;

    let sql = `
      SELECT 
        id, username, email, phone, avatar,
        CASE WHEN is_admin = 1 THEN 'admin' ELSE 'user' END as role,
        created_at
      FROM jd_users
      WHERE 1=1
    `;
    const params = [];

    if (keyword) {
      sql += ' AND (username LIKE ? OR email LIKE ? OR phone LIKE ?)';
      const searchTerm = `%${keyword}%`;
      params.push(searchTerm, searchTerm, searchTerm);
    }

    // 获取总数
    console.log('=== 步骤1: 获取总数 ===');
    const countSql = sql.replace(/SELECT[\s\S]*?FROM/, 'SELECT COUNT(*) as total FROM');
    console.log('COUNT SQL:', countSql);
    console.log('参数:', params);
    
    const [countResult] = await db.execute(countSql, params);
    const total = countResult[0].total;
    console.log('总数:', total);

    // 获取分页数据
    console.log('\n=== 步骤2: 获取分页数据 ===');
    sql += ' ORDER BY created_at DESC LIMIT ? OFFSET ?';
    params.push(parseInt(limit), parseInt(offset));
    console.log('查询SQL:', sql);
    console.log('参数:', params);
    
    const [users] = await db.execute(sql, params);
    console.log('查询到用户数:', users.length);
    
    console.log('\n=== 最终结果 ===');
    const result = {
      users,
      pagination: {
        page: parseInt(page),
        limit: parseInt(limit),
        total
      }
    };
    console.log(JSON.stringify(result, null, 2));

  } catch (error) {
    console.error('错误:', error.message);
    console.error('堆栈:', error.stack);
  } finally {
    process.exit(0);
  }
}

testUserListLogic();

